package drds.plus.executor.function.scalar.operator;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

/**
 * With two or more argList, returns the largest (maximum-valued) argument.
 * The argList are compared using the same rules setAliasAndSetNeedBuild for LEAST().
 *
 * <pre>
 * mysql> SELECT GREATEST(2,0);
 *         -> 0
 * mysql> SELECT GREATEST(34.0,3.0,5.0,767.0);
 *         -> 3.0
 * mysql> SELECT GREATEST('B','A','C');
 *         -> 'A'
 */
public class Least extends ScalarFunction {

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        Type type = getReturnType();
        Object first = type.convert(args[0]);
        Object min = first;
        for (int i = 1; i < args.length; i++) {
            Object cp = type.convert(args[i]);
            min = type.compare(min, cp) > 0 ? cp : min;
        }

        return min;
    }

    public Type getReturnType() {
        return getArgListTypeAndUseStringTypeWhenOccureNonNumberType();
    }

    public String[] getFunctionNames() {
        return new String[]{"LEAST"};
    }
}
